<template>
  <div class="anime-management">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="showUploadDialogs">上传番剧</el-button>
      <el-button
          type="danger"
          :disabled="selectedAnimes.length === 0"
          @click="batchDelete"
      >
        批量删除
      </el-button>

      <div class="search-box">
        <el-input
            v-model="searchQuery"
            placeholder="搜索番剧名称"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 番剧列表表格 -->
    <el-table
        v-loading="loading"
        :data="filteredAnimes"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="fileId" label="ID" width="80" />
      <el-table-column prop="title" label="番剧名称" width="180" />
      <el-table-column prop="fileSize" label="文件大小" width="280">
        <template #default="{row}">
          <span>{{ row.fileSize / 1024 / 1024 }} MB</span>
        </template>
      </el-table-column>
      <el-table-column prop="resolution" label="视频分辨率" width="180" />
      <el-table-column prop="episodeNumber" label="集数" width="100">
        <template #default="{row}">
          <span>{{ row.episodeNumber || 0 }}集</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="getStatusTagType(row.status)">
            <span v-if="row.status===0">审核</span>
            <span v-else>发布</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="上传时间" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button size="small" type="danger" @click="deleteAnime(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 上传番剧对话框 -->
    <VideoUPload
        ref="videouploadRef"
        :searchAnime="searchAnime"
        :animeOptions="animeOptions"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import VideoUPload from "@/components/VideoUPload.vue";
import {getVideoNameList} from "@/api/video.js";
import {loadFileDataList} from "@/api/videoFile.js";

// 数据状态
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedAnimes = ref([])
const animeOptions = ref([])
const videouploadRef = ref(null)

// 番剧搜索方法
const searchAnime = async (query) => {
  if (!query.trim()) return
  try {
    const res = await getVideoNameList({ keyword: query })
    animeOptions.value = res.data
  } catch (e) {
    ElMessage.error('搜索失败')
  }
}

//打开方法
const showUploadDialogs = () => {
  videouploadRef.value.openDialog()
}

// 表单数据
const animeList = ref([])

// 计算属性
const filteredAnimes = computed(() => {
  if (!searchQuery.value) return animeList.value
  return animeList.value.filter(item =>
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 生命周期钩子
onMounted(() => {
  fetchData()
})

// 方法定义
const fetchData = async () => {
  loading.value = true
  try {
    loading.value = false
    const res = await loadFileDataList(pageSize.value, currentPage.value, searchQuery.value)
    animeList.value = res.data.list
    total.value = res.data.totalCount
  } catch (error) {
    ElMessage.error('获取数据失败')
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const handleSearchClear = () => {
  searchQuery.value = ''
  fetchData()
}

const handleSelectionChange = (val) => {
  selectedAnimes.value = val
}

const batchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的番剧吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    animeList.value = animeList.value.filter(
        item => !selectedAnimes.value.some(selected => selected.id === item.id)
    )
    selectedAnimes.value = []
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const deleteAnime = (id) => {
  ElMessageBox.confirm('确定要删除该番剧吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    animeList.value = animeList.value.filter(item => item.id !== id)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    default: return ''
  }
}
</script>

<style scoped>
.anime-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-box {
  margin-left: auto;
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.ml-3 {
  margin-left: 10px;
}
</style>
